package com.mall.coupon.server.service.impl;

import com.mall.common.security.utils.SecurityUtils;
import com.mall.coupon.common.domain.CmsCoupon;
import com.mall.coupon.server.mapper.CmsCouponMapper;
import com.mall.coupon.server.service.CmsCouponService;
import com.mall.product.common.domain.PmsSkuInfo;
import com.mall.product.remote.feign.PmsSkuInfoRemote;
import com.mall.system.common.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class CmsCouponServiceImpl implements CmsCouponService {

    @Autowired
    private CmsCouponMapper cmsCouponMapper;

    @Autowired
    private PmsSkuInfoRemote pmsSkuInfoRemote;
    @Override
    public List<CmsCoupon> selectCmsCouponList(CmsCoupon cmsCoupon) {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        cmsCoupon.setShopId(loginUser.getUserid());
        return cmsCouponMapper.selectCmsCouponList(cmsCoupon);
    }



    @Override
    public void deleteCmsCouponByIds(Long[] ids) {

        for (Long id : ids) {
            CmsCoupon cmsCoupon = cmsCouponMapper.selectCmsCouponById(id);
            if (cmsCoupon.getActivityStatus() == 1){
                throw new RuntimeException("优惠券正在使用中，不能删除");
            }
        }

        cmsCouponMapper.deleteCmsCouponByIds(ids);
    }



    @Override
    public void updateCmsCoupon(Long id) {

        //只有优惠券的状态是使用中才可以把状态修改为失效
        CmsCoupon cmsCoupon = cmsCouponMapper.selectCmsCouponById(id);
        if (cmsCoupon.getActivityStatus() != 1){
            throw new RuntimeException("优惠券状态不是使用中，不能修改");
        }
        cmsCouponMapper.updateCouponStatus(id);
    }

    @Transactional
    @Override
    public void insertCmsCoupon(CmsCoupon cmsCoupon) {
        //获取当前登录人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        cmsCoupon.setShopId(loginUser.getUserid());
        cmsCouponMapper.insertCmsCoupon(cmsCoupon);

        //判断优惠券类型是通用还是指定商品
        if (cmsCoupon.getUseType() == 2){
            Long id = cmsCoupon.getId();
            List<Integer> skuIds = cmsCoupon.getSkuIds();
            cmsCouponMapper.insertSkuCoupon(id,skuIds);
        }
    }


}
